package com.pansoft.openplanet.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.TextView;

import com.efounder.chat.activity.BaseActivity;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.http.EFHttpRequest;
import com.efounder.util.LoadingDataUtilBlack;
import com.efounder.utils.ResStringUtil;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.pansoft.openplanet.R;
import com.pansoft.openplanet.adapter.CardStackAdapter;
import com.pansoft.openplanet.bean.Account;
import com.pansoft.openplanet.bean.PointCardBean;
import com.pansoft.openplanet.bean.StackItemBean;
import com.pansoft.openplanet.bean.WalletBean;
import com.pansoft.openplanet.cardstack.CardStackView;
import com.pansoft.openplanet.db.AccountDao;
import com.pansoft.openplanet.util.BalanceUtil;
import com.pansoft.openplanet.util.TCRequestUtil;
import com.utilcode.util.ToastUtils;

import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static com.efounder.frame.utils.Constants.CHAT_USER_ID;

public class StackActivity extends BaseActivity implements CardStackView.ItemExpendListener {

    private CardStackView mStackView;
    private CardStackAdapter mCardStackAdapter;
    private List<PointCardBean> pointCardBeans = new ArrayList<>();
    private List<WalletBean> walleatBeanList = new ArrayList<>();
    private AccountDao accountDao;
    private String silverDiamond = "";
    private String pwr = "";
    private String address = "";

    public static void start(Context context) {
        Intent starter = new Intent(context, StackActivity.class);
        context.startActivity(starter);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_card_stack);
        accountDao = new AccountDao(this);
//        initData();
        mStackView = (CardStackView) findViewById(R.id.stackview_main);
        mStackView.setItemExpendListener(this);
        mCardStackAdapter = new CardStackAdapter(this, intentListener);
        mStackView.setAdapter(mCardStackAdapter);
        TextView tvTitle = (TextView) findViewById(R.id.tv_title);
        tvTitle.setText(getString(R.string.open_planet_stack_recharge_title));

        new Handler().postDelayed(
                new Runnable() {
                    @Override
                    public void run() {
                        mCardStackAdapter.updateData(pointCardBeans);

                    }
                }
                , 200
        );
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (isFinishing()){
            LoadingDataUtilBlack.dismiss();
        }
    }

    private void initData() {
        //能量
        PointCardBean pwrBean = new PointCardBean();
        pwrBean.setCardId(1);
        pwrBean.setName(ResStringUtil.getString(R.string.open_planet_asset_mine_pwr_energy));
        pwrBean.setBackGround(R.drawable.open_planet_energy_currency1);
        pwrBean.setNum(address);
        pwrBean.setRecharge(false);
        pwrBean.setBalance(pwr);
        pwrBean.setIconLeft(R.drawable.energy_coin);
        pointCardBeans.add(pwrBean);
        //黑钻
        PointCardBean blackDiamondBean = new PointCardBean();
        blackDiamondBean.setCardId(2);
        blackDiamondBean.setName(ResStringUtil.getString(R.string.open_planet_asset_mine_pwr_black_diamond));
        blackDiamondBean.setBackGround(R.drawable.open_planet_black_diamond);
        blackDiamondBean.setNum(address);
        blackDiamondBean.setBalance("0");
        blackDiamondBean.setIconLeft(R.drawable.open_planet_black_diamond_left);
        blackDiamondBean.setRecharge(false);
        pointCardBeans.add(blackDiamondBean);
        //银钻
        PointCardBean silverDiamondBean = new PointCardBean();
        silverDiamondBean.setCardId(3);
        silverDiamondBean.setName(ResStringUtil.getString(R.string.open_planet_asset_mine_pwr_silver_diamond));
        silverDiamondBean.setBackGround(R.drawable.open_planet_silver_diamond);
        silverDiamondBean.setNum(address);
//        silverDiamondBean.setBalance(getIntent().getStringExtra("silverDiamond"));
        silverDiamondBean.setBalance(silverDiamond);
        silverDiamondBean.setIconLeft(R.drawable.open_planet_silver_diamond_left);
        silverDiamondBean.setRecharge(false);
        pointCardBeans.add(silverDiamondBean);

    }

    CardStackAdapter.ClickListener intentListener = new CardStackAdapter.ClickListener() {
        @Override
        public void onClick(View view, int position) {
            //可以充值跳转充值页面
            if (pointCardBeans.get(position).isRecharge()) {
                AmountRechargeActivity.start(StackActivity.this, pointCardBeans.get(position).getName()
                        , pointCardBeans.get(position).getCardId() + "");
                mStackView.clearSelectPosition();
            } else {
                //不能充值提醒等待开通
                new AlertDialog.Builder(StackActivity.this).setTitle(getString(R.string.open_planet_recharge_dredge_hint))
                        .setMessage(getString(R.string.open_planet_recharge_no_dredge))
                        .setCancelable(true)
                        .setPositiveButton(R.string.common_text_confirm, null).show();
            }

        }
    };

    @Override
    public void onItemExpend(boolean expend) {
//        mActionButtonContainer.setVisibility(expend ? View.VISIBLE : View.GONE);
    }

    /**
     * 获取fgt以及银钻余额
     */
    private void loadCardList() {
        LoadingDataUtilBlack.show(this, ResStringUtil.getString(R.string.common_text_loading));
        HashMap<String, String> map = new HashMap<>();
        map.put("phoneNumber", EnvironmentVariable.getUserName());
        map.put("address", EnvironmentVariable.getProperty("tc_ethAddress"));
        TCRequestUtil.getCommonRequest(TAG, "mallCard/getCardListDouble", map, new TCRequestUtil.TCRequestCallback() {
            @Override
            public void onSuccess(String response) {
                LoadingDataUtilBlack.dismiss();
                Gson gson = new GsonBuilder().serializeNulls().create();

                try {
                    StackItemBean StackItemBean = gson.fromJson(response, StackItemBean.class);
                    if (StackItemBean != null && StackItemBean.getResult().equals("success")) {
                        pointCardBeans.clear();
                        if (StackItemBean.getData().size() != 0) {
                            initData();
                            for (StackItemBean.DataBean dataBean : StackItemBean.getData()) {
                                PointCardBean cardBean = new PointCardBean();
                                cardBean.setName(dataBean.getCardEnName());
                                cardBean.setCardId(dataBean.getCardId());
                                cardBean.setBackGround(0);
                                String address = dataBean.getContractAddress();
                                cardBean.setNum(address.replace(address.substring(6, address.length() - 4), "****"));
                                //千分位，两位小数
                                String balance = BalanceUtil.formatPrice(dataBean.getBalance(), true, 2);
                                cardBean.setBalance(balance);
                                cardBean.setIconLeft(0);
                                cardBean.setCardImg(dataBean.getCardImg());
                                cardBean.setCardBg(dataBean.getBgImg());
                                if(dataBean.getAllowRecharge()==1){
                                    cardBean.setRecharge(true);
                                }else{
                                    cardBean.setRecharge(false);
                                }

                                pointCardBeans.add(cardBean);
                            }
//                            for(PointCardBean pointCardBean : pointCardBeans){
//                                if(pointCardBean.getCardId() == 5){
//                                    pointCardBean.setRecharge(false);
//                                }
//                            }
                        }

                        mCardStackAdapter.updateData(pointCardBeans);

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFail(String error) {
                LoadingDataUtilBlack.dismiss();
            }

        });
        //获取银钻余额
        HashMap<String, String> silverMap = new HashMap<>();
        silverMap.put("access_token", EnvironmentVariable.getProperty("tc_access_token"));
        TCRequestUtil.getOAuthRequest(TAG, "integral/integralTotal", silverMap, new TCRequestUtil.TCRequestCallback() {
            @Override
            public void onSuccess(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.optString("result").equals("success")) {
                        silverDiamond = BalanceUtil.formatPrice(Double.valueOf(jsonObject.optString("integralTotal")), true, 0);
                        for (PointCardBean pointCardBean : pointCardBeans) {
                            if (pointCardBean.getCardId() == 3) {

                                pointCardBean.setBalance(silverDiamond);
                            }
                        }
                        mCardStackAdapter.updateData(pointCardBeans);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFail(String error) {

            }
        });

    }

    //获取能量币余额
    private void getBanlancefromServer() {

        if (walleatBeanList.size() == 0) {
            // dismissLoading();
            //ToastUtil.showToast(getApplicationContext(), "请先添加新账户或者导入账户");
        } else {
            HashMap<String, String> map = new HashMap<>();
            map.put("ethAddress", walleatBeanList.get(0).getAddress());
            TCRequestUtil.postCommonRequest(TAG, "eth/ethGetBalance", map, new TCRequestUtil.TCRequestCallback() {
                @Override
                public void onSuccess(String response) {
                    JSONObject jsonObject = null;

                    try {
                        jsonObject = new JSONObject(response);
                        if (jsonObject != null && jsonObject.getString("result").equals("success")) {
                            String balance = jsonObject.getString("balance");
                            balance = BalanceUtil.balanceConvert(balance);
                            walleatBeanList.get(0).setBalance(balance);
                            if (balance.equals("0")) {
                                pwr = balance;
                            } else {
                                pwr = BalanceUtil.formatPrice(Double.valueOf(balance), true, 8);
                            }
                            for (PointCardBean pointCardBean : pointCardBeans) {
                                if (pointCardBean.getCardId() == 1) {

                                    pointCardBean.setBalance(pwr);
                                }
                            }
                            mCardStackAdapter.updateData(pointCardBeans);
//                            double cnyAmount = TCMathUtil.mul(Double.valueOf(balance), 100);
//                            tvCnyAmount.setText("￥ "+BalanceUtil.formatPrice(cnyAmount, true, 2));

                            //dismissLoading();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        // dismissLoading();
                    }
                }

                @Override
                public void onFail(String error) {
                    //dismissLoading();
                    ToastUtils.setBgColor(getResources().getColor(R.color.black));
                    ToastUtils.setMsgColor(getResources().getColor(R.color.op_text_white_color));
                    ToastUtils.showShort(ResStringUtil.getString(R.string.common_text_http_request_data_fail));
                }
            });
        }
    }

    //获取本地钱包地址
    private void getWallet() {

        Account mainAccount = new AccountDao(this).getMainAccount();
        if (mainAccount == null) {
            mainAccount = accountDao.getAccount(EnvironmentVariable.getProperty("tc_ethAddress"));
            if (mainAccount != null) {
                mainAccount.setMaster(true);
                mainAccount.setEnable(true);
                mainAccount.setImUserId(EnvironmentVariable.getProperty(CHAT_USER_ID));
                accountDao.insertOrReplace(mainAccount);
            } else {

            }
        }


        WalletBean walletBean = new WalletBean();
        walletBean.setAddress(mainAccount.getAddress());
        walletBean.setFile(new File(mainAccount.getFileName()));
        walletBean.setFilePath(mainAccount.getFileName());
        walletBean.setAccountName(mainAccount.getAcccountName());
        walletBean.setAvatar(mainAccount.getAccountAvatar());
        walleatBeanList.add(walletBean);
        address = walleatBeanList.get(0).getAddress();
        if (address.length() > 20) {
            address = address.replace(address.substring(6, address.length() - 4), "****");
        } else {
        }
        for (PointCardBean pointCardBean : pointCardBeans) {
            pointCardBean.setNum(address);
        }
        mCardStackAdapter.updateData(pointCardBeans);
    }

    @Override
    protected void onResume() {
        super.onResume();
        loadCardList();
        getWallet();
        getBanlancefromServer();
    }

    @Override
    protected void onStop() {
        super.onStop();
        EFHttpRequest.cancelRequest(TAG);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }
}

